/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Views.GestionRestaurant;

import Views.GestionRestaurateur.*;
import Controller.Controller;
import Model.Restaurateur;
import Views.GestionRestaurateur.RestaurateurPanel;
import Views.GestionRestaurateur.RestaurateurTablePanel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

/**
 *
 * @author ibrahim
 */
public class RestaurantFrame extends JFrame {
    private static final String title = "Gestion de Restaurant";
   
    private RestaurantPanel restaurantPanel;
    private RestaurantTablePanel tablePanel;
    private JFileChooser jfileChooser;
    private Controller controller;
    private PreferenceDialog prefDialog;
    private Preferences prefs;
     
    
        
    public RestaurantFrame() {
        super("Gestion de Restaurant");
        setMinimumSize(new Dimension(500, 400));
        
        setSize(600, 500);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setLayout(new BorderLayout());
        setJMenuBar( createMenuBar());
        this.controller = new Controller();
        try {
            loadDataFromDatabase();
        } catch (Exception ex) {
            Logger.getLogger(RestaurantFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
        
        
        
        this.restaurantPanel = new RestaurantPanel(this.controller);
        this.tablePanel = new RestaurantTablePanel(this.controller);
        this.jfileChooser = new JFileChooser();
        this.jfileChooser.addChoosableFileFilter(new RestaurateurFileFilter());
        
        this.prefDialog = new PreferenceDialog(this);
        this.prefs = Preferences.userRoot().node("db");
        
        add(restaurantPanel);
       
        
        
        
       
        
        this.tablePanel.setRestaurantTableListener(new RestaurantTableListener() {

           @Override
          public void rowDeleted(int row) {
              int id = controller.getRestaurateurId(row);
               System.out.println(id);
              int action = JOptionPane.showConfirmDialog(RestaurantFrame.this, 
                "Do you really want to remove this item from database ?", 
                "Confirm Exit", JOptionPane.OK_CANCEL_OPTION);
                if(action == JOptionPane.OK_OPTION){
              try {
                    controller.deleteRestaurateurFromDatabase(id);
                } catch (SQLException ex) {
                    Logger.getLogger(RestaurantFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                controller.removeRestaurateur(row);
               
               
            
               }
            }
        });

        this.restaurantPanel.setAddRestaurantListener(new AddRestaurantListener() {
           

            @Override
            public void AddRestaurantEventOccurred(AddRestaurantEvent e) {
                controller.saisirInformationRestaurant(e);
                System.out.println(e.getCity());
                
                
                
                
               tablePanel.refresh();
               clearTextFields(restaurantPanel);
            }
        });
        this.restaurantPanel.setSaveToDatabaseListener(new SaveToDatabaseListener() {

           @Override
           public void savetodatabaseEventOccured() {
                     
               try {
                   controller.saveRestaurantToDatabase();
                   if (controller.getResultAction().equals("Insertion")){
                       JOptionPane.showMessageDialog(RestaurantFrame.this,"Item(s) Successfully Added to Database !");
                  }
                   else{
                      JOptionPane.showMessageDialog(RestaurantFrame.this,"Item(s) Successfully Updated in Database !");
                   }
                   
                   
                
              } catch (SQLException ex) {
                 JOptionPane.showMessageDialog(RestaurantFrame.this,"Cannot Insert Data to Database", "Database Connection Error", JOptionPane.ERROR_MESSAGE);
 
              }
            }
       });
        

addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("Window closing");
                System.out.println("closing database connection");
                try {
                    controller.closeDatabaseConnection();
             } catch (SQLException ex) {
                    System.out.println("Cannot Close Database Connection");
                }
                dispose();
               System.gc();
            }
    
});

this.tablePanel.setData(this.controller.getRestaurants());
this.prefDialog.setPreferencelistener(new PreferenceListener() {

            @Override
            public void preferenceSet(String username, String password, int port) {
               prefs.put("username", username);
               prefs.put("password", password);
               prefs.putInt("port", port);
            }
        });
        String user = prefs.get("username", "");
        String password = prefs.get("password", "");
        int port = prefs.getInt("port", 3306);
        prefDialog.setDefaultPreferences(user, password, port);
        add(this.restaurantPanel, BorderLayout.WEST);
        add(new JScrollPane(tablePanel), BorderLayout.CENTER);
       
        
    }
    

    private JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        //File Menu
        JMenu fileMenu = new JMenu("File");
        JMenuItem exportDataItem = new JMenuItem("Export Data...");
        exportDataItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(jfileChooser.showSaveDialog(RestaurantFrame.this)==JFileChooser.APPROVE_OPTION){
                    try {
                        controller.saveRestaurantToFile(jfileChooser.getSelectedFile());
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(RestaurantFrame.this,
                                "Could not save data to file.", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        JMenuItem importDataItem = new JMenuItem("Import Data...");
        importDataItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK));
        importDataItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(jfileChooser.showOpenDialog(RestaurantFrame.this)==JFileChooser.APPROVE_OPTION){
                    try {
                        controller.loadRestaurantFromFile(jfileChooser.getSelectedFile());
                        tablePanel.refresh();
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(RestaurantFrame.this,
                                "Could not laod data from file.", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.setMnemonic(KeyEvent.VK_X);
        exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_MASK));
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int action = JOptionPane.showConfirmDialog(RestaurantFrame.this, 
                "Do you really want to exit the application ?", 
                "Confirm Exit", JOptionPane.OK_CANCEL_OPTION);
                if(action == JOptionPane.OK_OPTION){
                    WindowListener[] listeners =getWindowListeners();
                    for(WindowListener listener:listeners){
                        listener.windowClosing(new WindowEvent(RestaurantFrame.this,0));
                    }
              
                }
                
            }
        });
        fileMenu.add(exportDataItem);
        fileMenu.add(importDataItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        //Window Menu
        JMenu windowMenu = new JMenu("Window");
       JMenuItem windowMenuItem = new JMenuItem("Preferences");
        windowMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK));
       windowMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                prefDialog.setVisible(true);
            }
        });
        JMenu showMenu = new JMenu("Show");
        JCheckBoxMenuItem showMenuItem = new JCheckBoxMenuItem("Restaurant Form");
        showMenuItem.setSelected(true);
        showMenuItem.addActionListener(new ActionListener() {
           //Hiding Unhiding the Restaurateur Panel
            @Override
            public void actionPerformed(ActionEvent ev) {
                JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) ev.getSource();
                restaurantPanel.setVisible(menuItem.isSelected());

            }
        });
        
        windowMenuItem.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               
           }
        });

        showMenu.add(showMenuItem);
        windowMenu.add(showMenu);
        windowMenu.add(windowMenuItem);

        menuBar.add(fileMenu);
        menuBar.add(windowMenu);
        return menuBar;
    }
    private void clearTextFields (Container container){

      for(Component c : container.getComponents()){
       if(c instanceof JTextField){
          JTextField f = (JTextField) c;
          f.setText("");
                 } 
       else if (c instanceof Container)
     clearTextFields((Container)c);
      }
            }



    private void loadDataFromDatabase() throws Exception {
        controller.startDatabaseConnection();
        controller.loadRestaurateursFromDatabase();
        controller.loadRestaurantsFromDatabase();
        
        
    }

    public void commencerAjoutNewRestaurant() {
        setVisible(true);
        
    }

    
    
    
    
    
}



